const { DataTypes, Model } = require('sequelize');

module.exports = (sequelize) => {
  class UserFollow extends Model {
    // 检查是否已关注用户
    static async isFollowing(followedId, followerId) {
      // 确保ID是数字类型
      const targetUserId = parseInt(followedId, 10); // 被关注者ID
      const currentUserId = parseInt(followerId, 10); // 关注者ID
      
      const followRecord = await this.findOne({
        where: {
          follower_id: currentUserId, // 关注者ID（当前用户）
          followed_id: targetUserId, // 被关注者ID
          deleted_at: null
        }
      });
      return followRecord !== null;
    }

    // 关注用户
    static async followUser(followedId, followerId) {
      try {
        // 检查不能关注自己
        if (followedId === followerId) {
          throw new Error('不能关注自己');
        }

        // 检查是否已经关注
        const isAlreadyFollowing = await this.isFollowing(followedId, followerId);
        if (isAlreadyFollowing) {
          throw new Error('已经关注了该用户');
        }

        // 创建关注记录
        await this.create({
          follower_id: followerId, // 关注者（当前用户）
          followed_id: followedId  // 被关注者
        });

        return { success: true, followed: true };
      } catch (error) {
        return { success: false, error: error.message };
      }
    }

    // 取消关注用户 - 直接删除记录
    static async unfollowUser(followedId, followerId) {
      // 确保ID是数字类型
      const targetUserId = parseInt(followedId, 10); // 被关注者ID
      const currentUserId = parseInt(followerId, 10); // 关注者ID
      
      // 直接删除记录
      const deleted = await this.destroy({
        where: {
          follower_id: currentUserId, // 关注者（当前用户）
          followed_id: targetUserId, // 被关注者
          deleted_at: null
        }
      });
      
      return { 
        success: deleted > 0, 
        unfollowed: deleted > 0,
        message: deleted > 0 ? '取消关注成功' : '未找到关注记录'
      };
    }

    // 切换关注状态
    static async toggleFollow(followedId, followerId) {
      try {
        // 确保ID是数字类型
        const targetUserId = parseInt(followedId, 10); // 被关注者ID
        const currentUserId = parseInt(followerId, 10); // 关注者ID
        
        // 检查不能关注自己
        if (targetUserId === currentUserId) {
          return { success: false, error: '不能关注自己' };
        }

        // 首先检查是否存在未删除的关注记录
        const existingFollow = await this.findOne({
          where: {
            follower_id: currentUserId, // 关注者ID（当前用户）
            followed_id: targetUserId, // 被关注者ID
            deleted_at: null
          }
        });

        // 如果存在未删除的记录，则执行取消关注（软删除）
        if (existingFollow) {
          await this.destroy({
            where: {
              follower_id: currentUserId,
              followed_id: targetUserId
            },
            force: false // 软删除
          });
          return { success: true, followed: false, message: '取消关注成功' };
        }

        // 检查是否存在已软删除的记录
        const deletedFollow = await this.findOne({
          where: {
            follower_id: currentUserId,
            followed_id: targetUserId
          },
          paranoid: false // 包括已删除的记录
        });

        // 如果存在已软删除的记录，则恢复（更新deleted_at为null）
        if (deletedFollow) {
          await deletedFollow.restore();
          return { success: true, followed: true, message: '关注成功' };
        }

        // 如果记录完全不存在，则创建新记录
        try {
          await this.create({
            follower_id: currentUserId, // 关注者ID（当前用户）
            followed_id: targetUserId  // 被关注者ID
          });
          return { success: true, followed: true, message: '关注成功' };
        } catch (createError) {
          // 如果创建失败，可能是并发导致的重复关注
          console.error('创建关注记录时的错误:', createError);
          return { success: true, followed: true, message: '关注成功' };
        }
      } catch (error) {
        console.error('切换关注状态时出错:', error);
        return { success: false, error: error.message };
      }
    }

    /**
   * 获取用户关注的人列表
   */
  static async getUserFollowing(userId, limit = 20, offset = 0) {
    const sequelize = this.sequelize;
    const User = sequelize.models.User;
    
    return await this.findAll({
      where: {
        follower_id: userId, // userId是关注者，查找他关注的人
        deleted_at: null
      },
      include: [
        {
          model: User,
          as: 'followedUser', // 被关注者的用户信息
          attributes: ['id', 'username', 'nickname', 'avatar']
        }
      ],
      order: [['created_at', 'DESC']],
      limit,
      offset
    });
  }

  /**
   * 获取关注用户的粉丝列表
   */
  static async getUserFollowers(userId, limit = 20, offset = 0) {
    const sequelize = this.sequelize;
    const User = sequelize.models.User;
    
    return await this.findAll({
      where: {
        followed_id: userId, // userId是被关注者，查找关注他的人
        deleted_at: null
      },
      include: [
        {
          model: User,
          as: 'followerUser', // 关注者的用户信息
          attributes: ['id', 'username', 'nickname', 'avatar']
        }
      ],
      order: [['created_at', 'DESC']],
      limit,
      offset
    });
  }

  // 批量检查关注状态
  static async batchCheckFollowStatus(targetUserId, currentUserIds) {
    const follows = await this.findAll({
      where: {
        follower_id: currentUserIds,
        followed_id: targetUserId,
        deleted_at: null
      },
      attributes: ['follower_id']
    });
    
    const followerIdSet = new Set(follows.map(f => f.follower_id.toString()));
    return currentUserIds.map(id => ({
      userId: id,
      isFollowing: followerIdSet.has(id.toString())
    }));
  }

    // 获取用户关注数
    static async getFollowingCount(userId) {
      return await this.count({ 
        where: { 
          follower_id: userId, // userId是关注者，统计他关注的人数
          deleted_at: null 
        } 
      });
    }

    // 获取用户粉丝数
    static async getFollowersCount(userId) {
      return await this.count({ 
        where: { 
          followed_id: userId, // userId是被关注者，统计关注他的人数
          deleted_at: null 
        } 
      });
    }
  }

  UserFollow.init({
    follower_id: {
      type: DataTypes.BIGINT,
      allowNull: false,
      primaryKey: true
    },
    followed_id: {
      type: DataTypes.BIGINT,
      allowNull: false,
      primaryKey: true
    },
    created_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW
    },
    updated_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
      onUpdate: DataTypes.NOW
    },
    deleted_at: {
      type: DataTypes.DATE,
      allowNull: true
    }
  }, {
    sequelize,
    tableName: 'user_follow',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    deletedAt: 'deleted_at',
    paranoid: true
  });

  // 设置模型关联
  UserFollow.associate = (models) => {
    // 关联到关注者 (follower_id -> User.id)
    UserFollow.belongsTo(models.User, {
      foreignKey: 'follower_id',
      as: 'followerUser' // 关注者用户信息
    });
    
    // 关联到被关注者 (followed_id -> User.id)
    UserFollow.belongsTo(models.User, {
      foreignKey: 'followed_id',
      as: 'followedUser' // 被关注者用户信息
    });
  };

  return UserFollow;
};